<?php
/**
 * User: shx
 * Date: 2016/10/26
 * Time: 15:21
 */

namespace App\Helpers;

use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Intervention\Image\Facades\Image;

class UploadFile
{
    const RAW = 'raw';
    const EXT = 'jpg';
    const ROOT_DIR = '/upload';

    public static function save(UploadedFile $file, $save_dir = '/upload/archive')
    {
        //mkdir
        $root_dir = public_path(self::ROOT_DIR);
        if ( ! file_exists($root_dir)) mkdir($root_dir);

        $path = $file->getRealPath();
        $img = Image::make($path);

        $abs_dir = public_path($save_dir);
        if ( ! file_exists($abs_dir)) mkdir($abs_dir);

        $save_dir .= '/'.md5_file($path);

        $abs_dir = public_path($save_dir);
        if (!file_exists($abs_dir) && mkdir($abs_dir)) {
            $img->save("$abs_dir/".self::RAW.'.'.self::EXT);
        }

        return $save_dir;
    }

    public function read($uri, $size)
    {
        $sizes = explode('x', $size);

        $path = public_path($uri);
        if (!file_exists($path)) abort(404);

        try {
            $raw = public_path($uri) . "/" . self::RAW . '.';
            $raw .= file_exists($raw . self::EXT) ? self::EXT : 'jpeg';
            $img = Image::make($raw);

            if (!isset($sizes[1])) {
                //等比例缩放
                $img->widen((int)$sizes[0]);
            } elseif ($sizes[0] == 0) {
                $img->heighten((int)$sizes[1]);
            } else {
                $img->fit((int)$sizes[0], (int)$sizes[1]);
            }
            $img->save("{$uri}/{$size}." . self::EXT);

            return redirect(asset("$uri/$size." . self::EXT));
        } catch (\Exception $e) {
            return abort(404);
        }
    }
}